import React, { useRef, useEffect } from 'react';
import { useSelector } from 'react-redux';
import * as echarts from 'echarts';
interface Props { }
function BloodSugerEcharts(props: Props) {
    var myChart: any = null;
    let ChartRef = useRef(null)//使用useRef获取DOM元素
    const BloodSurgeList = useSelector((state: any) => { return state.WTreducer.BloodSurgeList })//从reducex中取出数据列表

    let getBloodSurgeList = async () => {
        if (BloodSurgeList) {
            let arrx = BloodSurgeList.map((item: any) => {//处理取出来的数据列表
                return item.bsTime
            })
            let arry = BloodSurgeList.map((item: any) => {//处理取出来的数据列表
                return item.bsValue
            })
            draw(arrx, arry)//绘图
        }

    }

    useEffect(() => {
        myChart = echarts.init(ChartRef.current || document.body)//确保获取得到的实例不会为空,否则echarts.init()会报错
        getBloodSurgeList()
        return () => { myChart.dispose() }//销毁myChart实例
    }, [BloodSurgeList])


    let draw = (X: any, Y: any) => {
        myChart.setOption({
            legend: {
                // data: [{ name: "fanqian" }, { name: "价格" }]
                // data: [{ name: "体重趋势" }]
            },
            title: { text: "血糖趋势" },
            xAxis: {
                type: 'category',
                data: X
            },
            yAxis: {
                type: 'value'
            },
            toolbox: {
                show: true,
                feature: {
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    dataView: { readOnly: false },
                    magicType: { type: ['line', 'bar'] },
                    restore: {},
                    saveAsImage: {}
                }
            },
            series: [
                {
                    name: "血糖",
                    data: Y,
                    type: 'line',
                    smooth: true
                },
            ]
        })
    }
    return (
        <div id='echarts' style={{ width: "100%", height: "500px" }} ref={ChartRef} ></div>
    );
}

export default BloodSugerEcharts;